<?php

namespace Api\Controller;

use Think\Controller;
use Think\Cache\RedisCache;
use Think\Api;
use Utils\Image;

class HomeController extends Controller {

    private $newsInfo = "newsInfo";
    private $resTime = 6;
    private $resultData = [];

    function __construct() {
        parent::__construct();
        $this->_redis = RedisCache::getIntance(RedisCache::REDIS_CMS);
    }

    public function newIndex() {
        $url = C("SITE_CMS") . '/CmsHome/getList';
        $param = [];
        $result = Api::request($url, $param, "post", $this->resTime);
        if ($result["index_focus"] && isset($result["index_focus"])) {
            self::dealFocus($result["index_focus"]);
        }
        if ($result["index_brand"] && isset($result["index_brand"])) {
            self::dealBrand($result["index_brand"]);
        }
        if ($result["index_channel"] && isset($result["index_channel"])) {
            self::dealChannel($result["index_channel"]);
        }
        exit(json_encode($this->resultData, JSON_UNESCAPED_UNICODE));
    }

    private function dealChannel($channelList) {
        foreach ($channelList as &$channel) {
            $channel["image_url"] = Image::getImgUrl($channel["image_url"]);
            unset($channel["content_id"]);
        }
        $this->resultData["index_channel"] = $channelList;
    }

    private function dealBrand($brandList) {
        foreach ($brandList as &$brand) {
            $brand["image_url"] = Image::getImgUrl($brand["image_url"]);
            unset($brand["content_id"]);
        }
        $this->resultData["index_brand"] = $brandList;
    }

    private function dealFocus($focusList) {
        foreach ($focusList as &$focus) {
            $focus["image_url"] = Image::getImgUrl($focus["image_url"]);
            unset($focus["content_id"]);
        }
        $this->resultData["index_focus"] = $focusList;
    }

    public function getAticleList() {
        $newsKey = $this->newsInfo;
        $articleList = $this->_redis->smembers($newsKey);
        $articleListUrl = [];
        foreach ($articleList as $key => $value) {
            if (strlen($value) > 0) {
                $httpPos = stripos($value, "http");
                $title = trim(substr($value, 0, $httpPos));
                $url = trim(substr($value, $httpPos));
                $articleListUrl[$key]["title"] = $title;
                $articleListUrl[$key]["url"] = $url;
            }
        }
        exit(json_encode($articleListUrl));
    }

}
